import {create, deleteById, findOne, list, update} from '@/services/pipeline-api';
import {PlusOutlined} from '@ant-design/icons';
import {formatDelay} from '@/utils/calculateUtil';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import {useLocation, useNavigate} from 'umi';
import {Button, Drawer, message, Modal, Space} from 'antd';
import React, {useRef, useState} from 'react';
import CreateOrUpdateForm from './components/CreateOrUpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.Pipeline) => {
  const hide = message.loading('正在添加');
  try {
    const res = await create({...fields});
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Pipeline) => {
  const hide = message.loading('更新中');
  try {
    const res = await update(fields);
    hide();

    if (res) {
      message.success('更细成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};


const Pipeline: React.FC = () => {

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [createOrUpdateModalOpen, handleCreateOrUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [isCreate, handleIsCreate] = useState<boolean>(true);
  const [count, setCount] = useState<number>(0);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Pipeline>();
  const location = useLocation();
  const navigate = useNavigate();
  // @ts-ignore
  const channelId = location?.state?.channelId || null;

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.Channel) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };
  const commonColumns: ProColumns<API.PipelineAggInfo>[] = [
    {
      title: '序号',
      dataIndex: 'id',
    },
    {
      title: 'Pipeline名字',
      dataIndex: 'name',
      tooltip: '查看/配置表映射',
      render: (dom, entity) => {
        return (
          <a onClick={() => {
            navigate('/admin/channel/pipeline/data-media-pair', {state: {channelId: entity?.channelId,pipelineId:entity?.id}})
          }}>{dom}</a>
        );
      },
    },
    {
      title: '并行度',
      dataIndex: ['parameters', 'parallelism'],
      hideInSearch:true
    },
    {
      title: '主站点',
      dataIndex: ['parameters', 'home'],
      renderText: (home: any) => home ? '是' : '否',
      hideInSearch:true
    }
  ]

  const descriptionColumns: ProColumns<API.Pipeline>[] = [
    ...commonColumns,
    {
      title: 'Select机器',
      dataIndex: ['selectNodes'],
      render: (_,record) => record?.selectNodes?.map(n => n.name)?.join(",")
    },
    {
      title: 'Load机器',
      dataIndex: ['loadNodes'],
      render: (_,record) => record?.loadNodes?.map(n => n.name)?.join(",")
    },
    {
      title: '数据反查线程数',
      dataIndex: ['parameters', 'extractPoolSize']
    },
    {
      title: '数据载入线程数',
      dataIndex: ['parameters', 'loadPoolSize']
    },
    {
      title: '文件载入线程数',
      dataIndex: ['parameters', 'fileLoadPoolSize']
    },
    {
      title: '同步数据来源',
      dataIndex: ['parameters', 'selectorMode']
    },
    {
      title: 'Canal名字',
      dataIndex: ['parameters', 'destinationName']
    },
    {
      title: '主道消费批次大小',
      dataIndex: ['parameters', 'mainstemBatchsize']
    },
    {
      title: '获取批次数据超时时间(毫秒)',
      dataIndex: ['parameters', 'batchTimeout']
    },
    {
      title: 'Load批次大小',
      dataIndex: ['parameters', 'loadBatchsize']
    },
    {
      title: '描述',
      dataIndex: ['parameters', 'description']
    },
    {
      title: '使用batch',
      dataIndex: ['parameters', 'useBatch'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '是否跳过Select异常',
      dataIndex: ['parameters', 'skipSelectException'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '是否跳过Load异常',
      dataIndex: ['parameters', 'skipLoadException'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '仲裁器调度模式',
      dataIndex: ['parameters', 'arbitrateMode'],
    },
    {
      title: '负载均衡算法',
      dataIndex: ['parameters', 'lbAlgorithm'],
    },
    {
      title: '传输模式',
      dataIndex: ['parameters', 'pipeChooseType'],
    },
    {
      title: '记录selector日志',
      dataIndex: ['parameters', 'dumpSelector'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '记录selector详细日志',
      dataIndex: ['parameters', 'dumpSelectorDetail'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '记录load日志',
      dataIndex: ['parameters', 'dumpEvent'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: 'dryRun模式',
      dataIndex: ['parameters', 'dryRun'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '支持ddl同步',
      dataIndex: ['parameters', 'ddlSync'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '跳过ddl异常',
      dataIndex: ['parameters', 'skipDdlException'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '文件重复同步对比',
      dataIndex: ['parameters', 'fileDetect'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '文件传输加密',
      dataIndex: ['parameters', 'useFileEncrypt'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '启用公网同步',
      dataIndex: ['parameters', 'useExternalIp'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '跳过自由门数据',
      dataIndex: ['parameters', 'skipFreedom'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '跳过反查无记录数据',
      dataIndex: ['parameters', 'skipNoRow'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '启用数据表类型转化',
      dataIndex: ['parameters', 'useTableTransform'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '兼容字段新增同步',
      dataIndex: ['parameters', 'enableCompatibleMissColumn'],
      renderText: (home: any) => home ? '是' : '否'
    },
    {
      title: '自定义同步标记',
      dataIndex: ['parameters', 'channelInfo'],
    },
  ];

  const columns: ProColumns<API.PipelineAggInfo>[] = [
    ...commonColumns,
    {
      title: 'mainstem状态',
      dataIndex: 'mainStem',
      renderText: (mainStem: API.MainStemEventData) => mainStem? mainStem?.status === 'TAKEING' ? '定位中' : '工作中' : '未工作',
      hideInSearch:true
    },
    {
      title: '延迟时间',
      dataIndex: ['delayStat', 'delayTime'],
      renderText: (d) => formatDelay(d),
      hideInSearch:true
    },
    {
      title: '最后同步时间',
      valueType: 'dateTime',
      dataIndex: ['throughput', 'gmtModified'],
      hideInSearch:true
    },
    {
      title: '最后位点时间',
      valueType: 'dateTime',
      dataIndex: ['positionDatas', 'modifiedTime'],
      hideInSearch:true
    },
    {
      title: '监控数',
      dataIndex: 'alarmRules',
      renderText: (alarmRules: any) => alarmRules ? alarmRules?.length : 0,
      hideInSearch:true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (<>
        <Space>
          <a
            key="detail"
            onClick={() => {
              setCurrentRow(record);
              setShowDetail(true);
            }}
          >
            查看
          </a>

          <a
            key="monitor"
            onClick={() => {
              navigate('/admin/channel/pipeline/data-media-pair', {state: {pipelineId: record?.id, channelId: record?.channelId,action:'monitor'}})
            }}
          >
            监控
          </a>

          <a
            key="log"
            onClick={() => {
              navigate('/admin/channel/pipeline/data-media-pair', {state: {pipelineId: record?.id,action:'log'}})
            }}
          >
            日志
          </a>

          {(!record?.channel?.status || record?.channel?.status === 'STOP') && (
            <>
              <a
                key="edit"
                onClick={() => {
                  handleCreateOrUpdateModalOpen(true);
                  handleIsCreate(false);
                  setCurrentRow(record);
                  setCount(count + 1);
                }}
              >
                编辑
              </a>
              {(!record?.pairs || record?.pairs?.length === 0) && (!record?.alarmRules || record?.alarmRules?.length === 0) && (
                <>
                  <a
                    type='button'
                    key="delete"
                    onClick={() => {
                      Modal.confirm({title: '确实删除?', onOk: () => handleRemove(record)});
                    }}
                  >删除
                  </a>
                </>
              )}
            </>
          )}
        </Space></>)

    }
  ];

  return (
    <PageContainer>
      <ProTable<API.Pipeline, API.PipelinePageRequest>
        headerTitle='Pipeline列表'
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleIsCreate(true);
              handleCreateOrUpdateModalOpen(true);
              setCount(count + 1);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={list}
        params={{channelId: channelId}}
        columns={columns}
      />
      <CreateOrUpdateForm
        refreshCount={count}
        onSubmit={async (value) => {
          let success;
          if (currentRow?.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleCreateOrUpdateModalOpen(false);
            setCurrentRow(undefined);
            await actionRef?.current?.reload();
          }
        }}
        title={isCreate? '新建':'编辑'}
        onCancel={() => {
          handleCreateOrUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={createOrUpdateModalOpen}
        values={isCreate? {channelId: channelId}  : currentRow }
      />

      <Drawer
        width={700}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.Pipeline>
            column={2}
            title={currentRow?.name}
            request={async () => findOne(currentRow?.id)}
            params={{
              id: currentRow?.id,
            }}
            columns={descriptionColumns as ProDescriptionsItemProps<API.Pipeline>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default Pipeline;
